import { useMemo } from 'react'

function useColumns(fields, chart) {
  const { indexEnabled, indexName, wordWrapEnabled, fixed, customFixed } = chart
  const columns = useMemo(() => {
    const ellipsis = !wordWrapEnabled
    const _columns = fields.map((v) => ({
      key: v.id,
      dataIndex: v.id,
      title: v.title,
      ellipsis
    }))
    if (indexEnabled) {
      _columns.unshift({
        title: indexName,
        width: 80,
        ellipsis,
        render: (text, record, index) => index + 1
      })
    }
    if (fixed?.enabled) {
      let left = 1,
        right = 0
      if (fixed.type === 'custorm') {
        left = customFixed.left
        right = customFixed.right
      }
      const len = _columns.length
      return _columns.map((v, i) => {
        if (i < left) {
          return { ...v, fixed: 'left' }
        }
        if (i >= len - right) {
          return { ...v, fixed: 'right' }
        }
        return v
      })
    }
    return _columns
  }, [fields])

  return columns
}

export default useColumns
